# -*- coding: UTF-8 -*-
# @Time : 2022/1/15 0015 13:34
# @Author : lyw RSW
# @Remark : 机柜
import random

from mxsoftpy import DB
from mxsoftpy.exception import DBError

from db.common.CRM.server_room import open_database, is_del, time_change
from index import _


class CabinetDB(DB):
    def __init__(self):
        """
        self.file : 数据库名
        self.main_key : 主键名
        self.path : 目录
        self.tag : 其他目录
        """
        self.file = 'Co_1'
        self.main_key = 'CRM'
        self.path = 'crm_overview'
        self.sroom_path = 'crm_config\\server_room'
        # self.tag = 'UNI_Tag'

        super().__init__()

    def list(self, parent, state, **search_dict):
        """
        机柜详情页
        :param parent: 目标机房组
        :param search_dict: 查询参数
        :return:
        """
        # self.path = self.sroom_path
        if parent == 'true' or parent == 'True':
            """查全部"""
            sroom_len, sroom_key_dict = open_database(self).filter(is_del=0, **search_dict)

        elif parent == 'false' or parent == 'False':
            """查未绑定"""
            sroom_len, sroom_key_dict = open_database(self).filter(parent='', is_del=0, **search_dict)
        elif parent.isdigit():
            """查指定机房下"""
            sroom_len, sroom_key_dict = open_database(self).filter(parent=parent, is_del=0, **search_dict)
        else:
            return 0, []

        if not sroom_len:
            return 0, []
        else:
            """整理数据"""
            data_dict = open_database(self).sub_items(key_list=sroom_key_dict)
            ret_list = []
            for data_key, data_val in data_dict.items():
                data_ret = self.re_test(data_val, data_key)
                print(state)
                if state:
                    if state == "0" and data_ret["state"] is False:
                        ret_list.append(data_ret)
                    elif state == "1" and data_ret["state"] is True:
                        ret_list.append(data_ret)
                else:
                    ret_list.append(data_ret)

            return sroom_len, ret_list

    def add(self, **kwargs):
        """
        添加机柜
        :param kwargs: 机柜的code
        :return:
        """
        print(kwargs)
        data_len, data_code_list = open_database(self).filter(name=kwargs['name'], is_del=0)
        if data_len > 0:
            return _('此机柜名称已存在')

        """添加数据"""
        code_int = open_database(self).insert_key_items(kwargs)

        return _('创建成功'), code_int

    def update(self, code, **kwargs):
        """
          更新机柜
          :param code: 需要更新 str
          :param kwargs: 更新的数据 dict
          :return:
          """
        """判断机房是否存在"""
        if int(is_del(self, code)) == 1:
            return _('操作完成'), _('无此机房')

        """判断名称是否存在"""
        if kwargs.get('name'):
            data_len, data_code_list = open_database(self).filter(name=kwargs['name'], is_del=0)
            if data_len > 0 and data_code_list[0] != code:
                return _('此机柜名称已存在')

        """更新数据"""
        open_database(self, code).insert_items(items=kwargs)

        return _('修改成功'), code

    def re_test(self, data_dict, code):
        """整理返回格式"""
        data_dict['cabinet_code'] = code
        data_dict['state'] = random.sample([False, True],1)[0]
        data_dict['cabinet_name'] = data_dict.pop('name')
        data_dict['cabinet_desc'] = data_dict.pop('desc')
        data_dict['available_space'] = data_dict['total_space'] - data_dict['binding_sd']
        data_dict.pop('is_del')
        data_dict['update_time'] = time_change(data_dict.pop('update_time'))
        parent_name = ''
        if data_dict['parent']:
            try:
                parent_name = self.tree.open(self.main_key, f"{self.sroom_path}\\{data_dict['parent']}",
                                             file=self.file).items(['parent_name', 'name'])
                parent_name = parent_name['parent_name'] + '/' + parent_name['name']
            except DBError:
                pass
        data_dict['parent_name'] = parent_name
        return data_dict

    def retrieve(self, code):
        """
        回显机柜
        :param code: 机柜的code
        :return:
        """
        data_dict = open_database(self, code).items()
        if data_dict['is_del']:
            return _('无此机柜')
        data_dict = self.re_test(data_dict, code)

        # data['device'] = 0
        return _('查询成功'), data_dict

    def select(self, code, parent):
        """
        添加已有的机柜
        :param code: 机柜的code
        :param parent: 机柜所属的机房
        :return:
        """
        code_list = code.split(';')
        tree = self.tree.open(self.main_key, f'{self.path}', file=self.file)
        tree.begin()
        try:
            for code_i in code_list:
                if code_i:
                    self.tree.open(self.main_key, f'{self.path}\\{code_i}', file=self.file).insert_item('parent',
                                                                                                        parent)
        except DBError:
            tree.rollback()
            return '添加失败'
        tree.commit()
        return '添加成功', '添加成功'

    def unbound(self, code):
        """
        移除的机柜
        :param code: 机柜的code
        :return:
        """
        code_list = code.split(';')
        tree = self.tree.open(self.main_key, f'{self.path}', file=self.file)
        tree.begin()
        try:
            for code_i in code_list:
                if code_i:
                    self.tree.open(self.main_key, f'{self.path}\\{code_i}', file=self.file).insert_item('parent', '')
        except DBError:
            tree.rollback()
            return '移除失败'
        tree.commit()
        return '移除成功', '移除成功'

    def delete(self, code):
        """
        删除的机柜
        :param code: 机柜的code
        :return:
        """
        code_list = code.split(';')
        tree = self.tree.open(self.main_key, f'{self.path}', file=self.file)
        tree.begin()
        try:
            for code_i in code_list:
                if code_i:
                    self.tree.open(self.main_key, f'{self.path}\\{code_i}', file=self.file).insert_item('is_del', 1)
        except DBError:
            tree.rollback()
            return '删除失败'
        tree.commit()
        return '删除成功', '删除成功'

    def distribution(self, code, parent):
        """
        分配机房
        :param code:
        :param parent:
        :return:
        """
        try:
            self.tree.open(self.main_key, f'{self.path}\\{code}', file=self.file).insert_item('parent', parent)
        except DBError:
            return '绑定失败'
        return '绑定成功', '绑定成功'
